package com.jiangnan.aop;

import com.jiangnan.mapper.OperateLogMapper;
import com.jiangnan.pojo.OperateLog;
import com.jiangnan.utils.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Aspect
@Slf4j
@Component
public class OperateLogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.jiangnan.anno.Log)")
    public Object logOperation(ProceedingJoinPoint joinPoint) throws Throwable {
        OperateLog operateLog = new OperateLog();
        
        // 设置操作人ID, 这里需要根据实际情况获取当前操作人信息
        operateLog.setOperateEmpId(getCurrentEmployeeId());
        operateLog.setOperateTime(LocalDateTime.now());
        operateLog.setClassName(joinPoint.getTarget().getClass().getName());
        operateLog.setMethodName(joinPoint.getSignature().getName());
        operateLog.setMethodParams(Arrays.toString(joinPoint.getArgs()));
        
        long startTime = System.currentTimeMillis();
        Object result = joinPoint.proceed(); // 执行目标方法
        long endTime = System.currentTimeMillis();
        
        operateLog.setReturnValue(result != null ? result.toString() : "null");
        operateLog.setCostTime(endTime - startTime);
        
        // 保存操作日志
        log.info("操作日志：{}", operateLog);
        operateLogMapper.insert(operateLog);

        return result;
    }

    // 获取当前操作人的ID，具体实现根据实际场景而定
    private Integer getCurrentEmployeeId() {
        // 实现获取当前登录用户ID的逻辑
        return CurrentHolder.getCurrentId(); // 示例返回值
    }
}